package com.cd.servlet;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cd.dao.StudentDao;
import com.cd.entity.Student;
import com.cd.util.PageResult;
import com.cd.vo.StudentVo;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
@WebServlet("/student")
public class StudentServlet extends HttpServlet {
	private StudentDao studentDao;

	@Override
	public void init() throws ServletException {
		studentDao = new StudentDao();
	}

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("application/json;charset=utf-8");
		req.setCharacterEncoding("utf-8");
		// 1. 获取请求参数cmd（区分前端的不同操作）
		String cmd = req.getParameter("cmd");
		// 2. 根据cmd的值，调用不同的方法处理不同的业务逻辑
		if (StrUtil.isNotBlank(cmd)) { // 相当于：cmd != null && cmd.trim().length() > 0
			if ("list".equals(cmd)) {   // 查询所有学生
				list(req,resp);
			}
			if("findByPage".equals(cmd)) {  // 分页查询
				findByPage(req,resp);
			}
			if("search".equals(cmd)) {      // 条件查询带分页
				search(req,resp);
			}
			if ("add".equals(cmd)) {        // 添加学生
				add(req,resp);
			}
			if ("update".equals(cmd)) {        // 修改学生
				update(req,resp);
			}
			if("delete".equals(cmd)) {          // 删除学生
				delete(req,resp);
			}
		}
	}
	// 删除学生
	private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取学号
		String sids = req.getParameter("sids");
		String[] split = sids.split(",");
		System.out.println("sids = " + sids);
		// 2. 删除学生
		studentDao.delete(split);
		// 3. 定义返回结果
		Map<String,String> map = new HashMap<>();
		map.put("code","200");
		map.put("message","删除学生成功！");
		// 4. 响应结果
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}

	// 添加学生
	private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 得到查询条件并转换为封装的java对象
		ObjectMapper objectMapper = new ObjectMapper();

		Student student = objectMapper.readValue(req.getInputStream(), Student.class);
		// 2. 定义返回结果
		Map<String,String> map = new HashMap<>();
		try {
			// 3. 添加学生
			studentDao.add(student);
			map.put("code","200");
			map.put("message","添加学生成功！");
		} catch (IOException e) {
			map.put("code","500");
			map.put("message","添加学生失败！");
		}
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}
	// 修改学生
	private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       // 1. 得到查询条件并转换为封装的java对象
		ObjectMapper objectMapper = new ObjectMapper();
		Student student = objectMapper.readValue(req.getInputStream(), Student.class);
		// 2. 修改学生
		studentDao.update(student);
		// 3. 定义返回结果
		Map<String,String> map = new HashMap<>();
		try {
			// 4. 修改学生
			studentDao.update(student);
			map.put("code","200");
			map.put("message","修改学生成功！");
		} catch (IOException e) {
			map.put("code","500");
			map.put("message","修改学生失败！");
		}
		resp.getWriter().write(JSONUtil.toJsonStr(map));
		resp.getWriter().flush();
	}
	// 查询学生信息
	private void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取分页参数
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = Integer.parseInt(req.getParameter("pageSize"));

		// 2. 得到查询条件并转换为封装的java对象
		ObjectMapper objectMapper = new ObjectMapper();
		StudentVo studentVo = objectMapper.readValue(req.getInputStream(), StudentVo.class);

		// 3. 开始分页带条件查询
		PageResult<Student> pageResult = studentDao.search(page,pageSize,studentVo);
		String json = JSONUtil.toJsonStr(pageResult);
		resp.getWriter().write(json);
		resp.getWriter().flush();
	}

	// 分页查询
	private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 获取分页参数
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = Integer.parseInt(req.getParameter("pageSize"));
		PageResult<Student> pageResult = studentDao.findByPage(page,pageSize);
		String json = JSONUtil.toJsonStr(pageResult);
		resp.getWriter().write(json);
		resp.getWriter().flush();
	}

	// 列表学生
	private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 1. 查询所有学生
		List<Student> students = studentDao.findAll();
		// 2. 转换为json字符串并送到前端
		String json = JSONUtil.toJsonStr(students);
		resp.getWriter().write(json);
		resp.getWriter().flush();
	}
}
